#include <fstream>
#include <string>

#include "translations.h"

namespace
{
crow::json::wvalue loadFile(const std::string& lang)
{
    std::ifstream file("translations/" + lang + ".json");
    if (!file.is_open())
        return {};

    const std::string fileContents(
        (std::istreambuf_iterator<char>(file)),
        std::istreambuf_iterator<char>()
    );
    return crow::json::load(fileContents);
}
} // namespace

namespace Ui
{

Translations& Translations::getInstance()
{
    static Translations instance;
    return instance;
}

crow::json::wvalue Translations::data(const std::string& lang) const
{
    auto dataIterator = m_data.find(lang);
    if (dataIterator != m_data.end())
        return dataIterator->second;

    dataIterator = m_data.find(defaultLang());
    if (dataIterator != m_data.end())
        return dataIterator->second;

    return {};
}

std::vector<std::string> Translations::langs() const
{
    std::vector<std::string> result;
    result.reserve(m_data.size());
    for (auto [lang, json] : m_data)
        result.push_back(lang);
    return result;
}

std::string Translations::defaultLang() const
{
    return "ru";
}

void Translations::loadLang(const std::string& lang)
{
    const auto json = loadFile(lang);
    if (0 != json.size())
        m_data.emplace(lang, json);
}

Translations::Translations()
{
    loadLang("ru");
    loadLang("eo");
}

} // namespace Ui
